﻿using System;
using System.Data;
using System.Web.UI;
using Model;
using Resources;
using Service;

public partial class workOrderAddAdmin : Page
{
    private readonly WODirectService _WODirectService = new WODirectService();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["workOrder"] != null) DisplayDetailWorkOrder((WorkOrder) Session["workOrder"]);
            if (Session["planning"] != null) DisplayDetailPlanning((Planning) Session["planning"]);
            if (Session["workOrderTask"] != null) DisplayWorkOrderTask((WorkOrderTask) Session["workOrderTask"]);

            if (Request.QueryString["codeNumber"] != null)
            {
                txtEquipCodeNumber.Text = Request.QueryString["codeNumber"];
                LoadProblemGroup();
            }
            if (Session["requiredDate"] != null)
            {
                DateTime requireDate = new Utility().ConvertToCustomizedFormat(Session["requiredDate"]);
                if (requireDate.Equals(DateTime.Parse(Resource.EmptylDateTime)))
                    txtPlanDate.Text = requireDate.ToString(Resource.DateEnglishFormat);
                else txtPlanDate.Text = string.Empty;
            }

            // CLEAR ALL  SESSION  
             ClearSessions();

        }
    }
    private void ClearSessions()
    {
        Session["workOrder"] = null;
        Session["planning"] = null;
        Session["workOrderTask"] = null;
        Session["requiredDate"] = null;
        Session["department"] = null;
        Session["codeOwner"] = null;
        Session["planTime"] = null;
        Session["assignEmployeeId"] = null;
        Session["oringalPage"] = null;
    }

    private void DisplayDetailWorkOrder(WorkOrder workOrder)
    {
        drlCriteria.SelectedValue = workOrder.CriteriaId.ToString();
        drlRequestType.SelectedValue = workOrder.RequestMadeById.ToString();
        txtRequestDate.Text = workOrder.RequestDate.ToString(Resource.DateEnglishFormat);
        if (!workOrder.AgreedDate.Equals(DateTime.Parse(Resource.EmptylDateTime)))
            txtAgreeDate.Text = workOrder.AgreedDate.ToString(Resource.DateEnglishFormat);
        else txtAgreeDate.Text = string.Empty;
        txtRequestTime.Text = workOrder.RequestTime.Hour + " : " + workOrder.RequestTime.Minute;
        if (Session["department"] != null)
            drlDepartment.SelectedValue = Session["department"].ToString();
        if (drlRequester.SelectedIndex != -1)
            drlRequester.SelectedValue = workOrder.RequesterId.ToString();
        drlEquipmentOwner.SelectedValue = workOrder.EmployeeId.ToString();

        if (drlEquipmentOwner.SelectedIndex != -1)
            drlEquipmentOwner.SelectedValue = workOrder.EmployeeId.ToString();
    }

    private void DisplayDetailPlanning(Planning planning)
    {
        drlITStaff.SelectedValue = planning.EmployeeId.ToString();
        txtEstimatedTime.Text = planning.EstimateTimeInMinute.ToString();
        if (!planning.PlanningDate.Equals(DateTime.Parse(Resource.EmptylDateTime)))
            txtPlanDate.Text = planning.PlanningDate.ToString(Resource.DateEnglishFormat);
        else txtPlanDate.Text = string.Empty;
        if (planning.PlanningTime != null)
            txtPlanTime.Text = planning.PlanningTime.Hour + " : " + planning.PlanningTime.Minute;
        else txtPlanTime.Text = string.Empty;

        if (Session["planTime"] != null)
        {
            txtPlanTime.Text = ((DateTime) Session["planTime"]).Hour + " : " + ((DateTime) Session["planTime"]).Minute;
            txtPlanDate.Text = new Utility().ConvertToDisplayDateString((DateTime) Session["planTime"]);
        }
        drlPriority.SelectedValue = planning.Priority.ToString();
        txtRemark.Text = planning.Remark;
    }

    private void DisplayWorkOrderTask(WorkOrderTask task)
    {
        txtRequiredDate.Text = task.RequiredDate.ToString(Resource.DateEnglishFormat);
        txtEquipCodeNumber.Text = task.EquipmentCodeNumber;


        txtNewProblem.Text = task.ProposedProblem;

        LoadProblemGroup();
    }

    protected void txtWorkOrderNumber_TextChanged(object sender, EventArgs e)
    {
        DataTable rowFound = _WODirectService.IsCodeNumberExist(txtEquipCodeNumber.Text);
        if (rowFound.Rows.Count == 0)
        {
            lblInformation.Text = Resource.MsgEquipmentCodeInCorrect;
            return;
        }

        lblInformation.Text = string.Empty;
        txtHiddenCodeNumber.Text = rowFound.Rows[0]["typeEquipementID"].ToString();

        drlProblem.DataSource =
            new ReferenceDataDirectService().GetProblemByTypeEquipmentId(Int32.Parse(txtHiddenCodeNumber.Text));
        drlProblem.DataValueField = "GROUPEPROBLEMID";
        drlProblem.DataTextField = "GROUPEPROBLEM";
        drlProblem.DataBind();
    }

    protected void btnValidate_Click(object sender, EventArgs e)
    {
    }

    private Planning GetPlanning(int taskId)
    {
        Utility _Uitility = new Utility();
        Planning planning = new Planning();
        planning.EmployeeId = Int32.Parse(drlITStaff.SelectedValue);
        planning.EstimateTimeInMinute = !String.IsNullOrEmpty(txtEstimatedTime.Text)
                                            ? _Uitility.ConvertToInteger(txtEstimatedTime.Text)
                                            : 0;
        planning.PlanningDate = _Uitility.ConvertToCustomizedFormat(txtPlanDate.Text);

        if (!String.IsNullOrEmpty(txtPlanTime.Text))
            planning.PlanningTime = DateTime.Parse(txtPlanTime.Text);
        else planning.PlanningTime = DateTime.Parse(DateTime.Now.Hour + ":" + DateTime.Now.Minute);

        planning.Priority = Int32.Parse(drlPriority.SelectedValue);
        planning.Remark = txtRemark.Text;
        planning.TaskId = taskId;
        return planning;
    }

    private WorkOrderTask GetWorkOrderTask(int workOrderId, int problemId, string problem)
    {
        Utility _Utility = new Utility();
        WorkOrderTask workOrderTask = new WorkOrderTask();
        workOrderTask.RequiredDate = _Utility.ConvertToCustomizedFormat(txtRequiredDate.Text);
        workOrderTask.EquipmentCodeNumber = txtEquipCodeNumber.Text;
        workOrderTask.ProblemId = problemId;
        workOrderTask.WorkOrderId = workOrderId;
        workOrderTask.IsCancel = false;
        workOrderTask.ProposedProblem = problem;
        return workOrderTask;
    }
    private WorkOrderTask GetWorkOrderTask(int workOrderId)
    {
        Utility _Utility = new Utility();
        WorkOrderTask workOrderTask = new WorkOrderTask();
        workOrderTask.RequiredDate = _Utility.ConvertToCustomizedFormat(txtRequiredDate.Text);
        workOrderTask.EquipmentCodeNumber = txtEquipCodeNumber.Text;
        workOrderTask.WorkOrderId = workOrderId;
        workOrderTask.IsCancel = false;
        
        return workOrderTask;
    }
    private WorkOrder GetWorkOrder()
    {
        Utility _Utility = new Utility();
        WorkOrder workOrder = new WorkOrder();
        workOrder.CriteriaId = Int32.Parse(drlCriteria.SelectedValue);
        workOrder.RequestMadeById = Int32.Parse(drlRequestType.SelectedValue);
        workOrder.EmployeeId = Int32.Parse(drlEquipmentOwner.SelectedValue);
        workOrder.RequesterId = Int32.Parse(drlRequester.SelectedValue);
        workOrder.Authorized = false;
        workOrder.RequestDate = _Utility.ConvertToCustomizedFormat(txtRequestDate.Text);
        workOrder.AgreedDate = _Utility.ConvertToCustomizedFormat(txtAgreeDate.Text);

        if (!String.IsNullOrEmpty(txtRequestTime.Text))
            workOrder.RequestTime = DateTime.Parse(txtRequestTime.Text);
        else workOrder.RequestTime = DateTime.Parse(DateTime.Now.Hour + ":" + DateTime.Now.Minute);
        return workOrder;
    }

    private bool ValidateDataWorkOrderPart()
    {
        if (drlDepartment.SelectedIndex == 0)
        {
            lblRequiredDepartment.Text = Resource.MessInformSelectAValue;
            return false;
        }
        lblRequiredDepartment.Text = string.Empty;

        if (drlRequester.SelectedIndex == -1)
        {
            lblRequiredRequestName.Text = Resource.MessInformSelectAValue;
            return false;
        }
        lblRequiredRequestName.Text = string.Empty;

        if (drlRequestType.SelectedIndex == 0)
        {
            lblRequiredRequestType.Text = Resource.MessInformSelectAValue;
            return false;
        }
        lblRequiredRequestType.Text = string.Empty;

        if (drlCriteria.SelectedIndex == 0)
        {
            lblRequiredCriteria.Text = Resource.MessInformSelectAValue;
            return false;
        }
        lblRequiredCriteria.Text = string.Empty;
        if (String.IsNullOrEmpty(txtRequestDate.Text))
        {
            lblRequiredRequestDate.Text = Resource.MsgFillInformation;
            return false;
        }
        lblRequiredRequestDate.Text = string.Empty;
        if (String.IsNullOrEmpty(txtRequiredDate.Text))
        {
            lblRequiredDate.Text = Resource.MessInformSelectAValue;
            return false;
        }
        lblRequiredDate.Text = string.Empty;
        if (String.IsNullOrEmpty(txtAgreeDate.Text))
        {
            lblAgreeDate.Text = Resource.MessInformSelectAValue;
            return false;
        }
        lblAgreeDate.Text = string.Empty;

        if (!String.IsNullOrEmpty(txtRequestTime.Text))
        {
            if (!new Utility().verifyTimeFormat(txtRequestTime.Text))
            {
                lblRequiredRequestTime.Text = Resource.MsgNotCorrectTimeFormat;
                return false;
            }
            lblRequiredRequestTime.Text = string.Empty;
        }
        lblRequiredRequestTime.Text = string.Empty;

       
        return true;
    }

    private bool ValidateOwnerPart()
    {
        if (drlEquipmentOwner.SelectedIndex < 0)
        {
            lblRequiredOwner.Text = Resource.MessInformSelectAValue;
            return false;
        }
        lblRequiredOwner.Text = string.Empty;
        return true;
    }

    private bool ValidateProblemPart()
    {
        if (String.IsNullOrEmpty(txtEquipCodeNumber.Text))
        {
            lblRequiredCodeNumber.Text = Resource.MsgFillInformation;
            return false;
        }
        lblRequiredCodeNumber.Text = string.Empty;

        if (drlProblem.SelectedIndex == -1)
        {
            lblRequiredProblemGroup.Text = Resource.MessInformSelectAValue;
            return false;
        }
        lblRequiredProblemGroup.Text = string.Empty;


        if (String.IsNullOrEmpty(txtNewProblem.Text))
        {
            lblRequiredProblem.Text = Resource.MsgFillInformation;
            return false;
        }
        lblRequiredProblem.Text = string.Empty;
        return true;
    }

    private bool ValidatePlanTime()
    {
        if (!String.IsNullOrEmpty(txtPlanTime.Text))
        {
            if (!new Utility().verifyTimeFormat(txtPlanTime.Text))
            {
                lblRequiredPlanTime.Text = Resource.MsgNotCorrectTimeFormat;
                return false;
            }
            lblRequiredPlanTime.Text = string.Empty;
        }
        lblRequiredPlanTime.Text = string.Empty;
        return true;
    }

    protected void btnValidateWorkOrder_Click(object sender, EventArgs e)
    {
        if (!new Utility().TestPermissions(Resource.PermissionAddWorkOrderAdmin))
        {
            lblPermission.Text = Resource.Permission;
            return;
        }
        try
        {
            if (!ValidateDataWorkOrderPart()) return;
            if (!ValidateOwnerPart()) return;
            if (!ValidateProblemPart()) return;
            if (!ValidatePlanTime()) return;

            //insert into  workorder 
            Utility _Utility = new Utility();
            WorkOrderService _WorkOrderService = new WorkOrderService();

            WorkOrder workOrder = GetWorkOrder();
            if (!String.IsNullOrEmpty(txtHiddenWorkOrderId.Text))
                workOrder.WorkorderId = _Utility.ConvertToInteger(Session["workOrderId"]);

            _WorkOrderService.SaveWorkOrder(workOrder);
            txtHiddenWorkOrderId.Text = workOrder.WorkorderId.ToString();


            //add new problem if not exist
            Problem problem = new Problem();
            if (!String.IsNullOrEmpty(txtNewProblem.Text))
            {
                int groupProbId = _Utility.ConvertToInteger(drlProblem.SelectedValue);

                problem = _WorkOrderService.IsAlreadyExistProblem(groupProbId, txtNewProblem.Text);
                if (problem.ProblemId == 0)
                {
                    problem.GroupProblemId = groupProbId;
                    problem.ProblemLabel = txtNewProblem.Text;
                    _WorkOrderService.SaveProblem(problem);
                }
            }


            // add  taskInworkorder
            WorkOrderTask workOrderTask = GetWorkOrderTask(workOrder.WorkorderId,
                                                           _Utility.ConvertToInteger(drlProblem.SelectedValue),
                                                           txtNewProblem.Text);
            _WorkOrderService.SaveWorkOrderTask(workOrderTask);

            if (drlITStaff.SelectedIndex != 0)
            {
                Planning planning = GetPlanning(workOrderTask.WorkOrderTaskId);
                new PlanningService().SavePlanning(planning);
            }

            // send mail to it , requester and it employee being assigned

            //WODirectService sendmailConfirm = new WODirectService();
            ////int userlocation = Convert.ToInt32(Request.ServerVariables["REMOTE_ADDR"].Substring(7, 2));
            ////string itaddress = "";

            ////if (userlocation == 28 || userlocation == 29)
            ////{
            ////    itaddress = "pnh.it.support@cambodia-airports.aero";
            ////}
            ////else if (userlocation == 30)
            ////{
            ////    itaddress = "rep.it.support@cambodia-airports.aero";
            ////}
            ////else if (userlocation == 31)
            ////{
            ////    itaddress = "kos.it.support@cambodia-airports.aero";
            ////}
            //sendmailConfirm.sendConfirmWorkorder(workOrder.WorkorderId, txtEquipCodeNumber.Text, problem.ProblemLabel, "chantha.kd@gmail.com");
            // adding planning 


            //if(drlITStaff.SelectedIndex != 0 ){
            //Employee employee  = new ReferenceDataService().GetEmployeeById(Int32.Parse(drlITStaff.SelectedValue));
            //if(!String.IsNullOrEmpty(employee.EmailAddress))
            //sendmailConfirm.sendConfirmWorkorder(workOrder.WorkorderId, txtEquipCodeNumber.Text, problem.ProblemLabel, employee.EmailAddress);
            
            //lblInformation.Text = Resource.MessageValidate;

            lblInformation.Text = "Work order Nº :" + workOrder.WorkorderId + " has been added successfully";
        }

        catch (Exception ex)
        {
            lblInformation.Text = ex.Message;
            throw ex;
        }
    }

    protected void btnCancelWorkOrder_Click(object sender, EventArgs e)
    {
        ClearWorkOrderFields();
    }

    private void ClearWorkOrderFields()
    {
        txtEquipCodeNumber.Text = string.Empty;
        txtNewProblem.Text = string.Empty;
        txtRequestDate.Text = string.Empty;
        txtEstimatedTime.Text = string.Empty;
        txtAgreeDate.Text = string.Empty;
        txtPlanDate.Text = string.Empty;
        txtPlanTime.Text = string.Empty;
        txtRemark.Text = string.Empty;
        txtRequestTime.Text = string.Empty;
        txtRequiredDate.Text = string.Empty;
        


        drlRequestType.SelectedIndex = -1;
        drlRequester.SelectedIndex = -1;
        drlCriteria.SelectedIndex = -1;
        drlDepartment.SelectedIndex = -1;
        drlProblem.SelectedIndex = -1;
        drlEquipmentOwner.SelectedIndex = -1;
        drlITStaff.SelectedIndex = -1;
        drlPriority.SelectedIndex = -1;
       
    }

    protected void txtEquipCodeNumber_TextChanged(object sender, EventArgs e)
    {
        LoadProblemGroup();
    }

    private void LoadProblemGroup()
    {
        DataTable rowFound = _WODirectService.IsCodeNumberExist(txtEquipCodeNumber.Text);
        if (rowFound.Rows.Count == 0)
        {
            lblInformation.Text = Resource.MsgEquipmentCodeInCorrect;
            return;
        }

        lblInformation.Text = string.Empty;
        txtHiddenCodeNumber.Text = rowFound.Rows[0]["typeEquipementID"].ToString();
        drlProblem.DataSource =
            new ReferenceDataDirectService().GetProblemByTypeEquipmentId(Int32.Parse(txtHiddenCodeNumber.Text));
        drlProblem.DataValueField = "GROUPEPROBLEMID";
        drlProblem.DataTextField = "GROUPEPROBLEM";
        drlProblem.DataBind();
    }

    protected void imgButton_Click(object sender, ImageClickEventArgs e)
    {
        if (drlEquipmentOwner.SelectedIndex >= 0)
        {
            if (!ValidateDataWorkOrderPart()) return;
            if (!ValidateProblemPart()) return;

            if (!String.IsNullOrEmpty(txtRequiredDate.Text))
            {
                Session["requiredDate"] = new Utility().ConvertToCustomizedFormat(txtRequiredDate.Text);
                Session["assignEmployeeId"] = drlITStaff.SelectedValue;
                WorkOrder workOrder = GetWorkOrder();
                Session["workOrder"] = workOrder;
                
                WorkOrderTask workOrderTask = GetWorkOrderTask(workOrder.WorkorderId,
                                                              Int32.Parse(drlProblem.SelectedValue), txtNewProblem.Text);
                Session["workOrderTask"] = workOrderTask;
                Session["planning"] = GetPlanning(workOrderTask.WorkOrderTaskId);
                Session["department"] = drlDepartment.SelectedValue;
                ​​lblInformation.Text = string.Empty;
                Session["oringalPage"] = "./workOrderAddAdmin.aspx";
                Response.Redirect("./laborResourceView.aspx?day=" + txtRequiredDate.Text);

            }
            else
                lblInformation.Text = "Selected requested date and IT Staffs to see their schedule !";
        }

        {
            lblInformation.Text = "Selected requested date and IT Staffs to see their schedule !";
        }
    }

    protected void ImgCodeInformation_Click(object sender, ImageClickEventArgs e)
    {
        if (!ValidateDataWorkOrderPart()) return;
        if (drlEquipmentOwner.SelectedIndex >= 0)
        {
            WorkOrder workOrder = GetWorkOrder();
            Session["workOrder"] = workOrder;
            WorkOrderTask workOrderTask = GetWorkOrderTask(workOrder.WorkorderId);
            Session["workOrderTask"] = workOrderTask;
            Session["requiredDate"] = new Utility().ConvertToCustomizedFormat(txtRequiredDate.Text);

            // Session["planning"] = GetPlanning(workOrderTask.WorkOrderTaskId);

            Session["department"] = drlDepartment.SelectedValue;
            Session["codeOwner"] = Int32.Parse(drlEquipmentOwner.SelectedValue);
            lblInformation.Text = string.Empty;
            Response.Redirect("./UserEquipmentCode.aspx");

        }

        else
        {
            lblInformation.Text = "Select equipment owner first !";
        }
    }

    protected void drlProblem_SelectedIndexChanged(object sender, EventArgs e)
    {
    }
}